import { formatSongTime } from "../common";

export function createProgressBar(type, btn, mediaEle, config) {
    if (!btn) return console.error('Cannot find the dom!');
    let btnWidth = btn.getBoundingClientRect().width,
        parent = btn.parentNode,
        parentWith = parent.getBoundingClientRect().width,
        curBar = btn.nextElementSibling,
        gap = 0;
    if (type === 2) {
        let curRatio = mediaEle.volume / 1;
        btn.style.left = `${curRatio * parentWith - 0.5 * btnWidth}px`;
        curBar.style.width = `${curRatio * parentWith}px`;
        volumeUpdate(mediaEle, config);
    } else {
        btn.style.left = `${-0.5 * btnWidth}px`;
        curBar.style.width = `${0}px`;
    }
    function moveHandler(e) {
        e.stopPropagation();
        let clientX = e.touches ? e.changedTouches[0].clientX : e.clientX,
            boundingClientRectX = clientX - gap,
            newX = boundingClientRectX - this.parentNode.getBoundingClientRect().x,
            newWidth = boundingClientRectX - this.nextElementSibling.getBoundingClientRect().x + (btnWidth / 2),
            curRatio = newWidth / parentWith,
            newTime = curRatio * mediaEle.duration,
            leftBoundary = parent.getBoundingClientRect().x - (btnWidth / 2),
            rightBoundary = parent.getBoundingClientRect().x + parentWith - (btnWidth / 2);

        if (boundingClientRectX >= leftBoundary && boundingClientRectX <= rightBoundary) {
            this.style.left = `${newX}px`;
            curBar.style.width = `${newWidth}px`;
            if (type === 1) musicPlayerUpdate(config.curTime, mediaEle, newTime);
            if (type === 2) mediaEle.volume = curRatio >= 1 ? 1 : curRatio;
            if (type === 3) videoPlayerUpdate(mediaEle, newTime);
        }
    }
    btn.ontouchstart = function (e) {
        e.stopPropagation();
        gap = e.changedTouches[0].clientX - this.getBoundingClientRect().x;
        this.className = "dot-button focus";
        btn.ontouchmove = moveHandler.bind(this);
        btn.ontouchend = function (e) {
            document.ontouchmove = null;
            this.className = "dot-button";
            let clientX = e.touches ? e.changedTouches[0].clientX : e.clientX,
                newWidth = clientX - this.parentNode.getBoundingClientRect().x,
                newLeft = newWidth - 0.5 * btnWidth,
                curRatio = newWidth / parentWith,
                newTime = curRatio * mediaEle.duration;
            if (type === 1) musicPlayerUpdate(config.curTime, mediaEle, newTime);
            if (type === 2) mediaEle.volume = curRatio >= 1 ? 1 : curRatio;
            if (type === 3) videoPlayerUpdate(mediaEle, newTime);
            this.style.left = `${newLeft}px`;
            curBar.style.width = `${newWidth}px`;
        };
    }
    parent.ontouchstart = function (e) {
        e.stopPropagation();
        let clientX = e.touches ? e.changedTouches[0].clientX : e.clientX,
            newWidth = clientX - this.getBoundingClientRect().x,
            newLeft = newWidth - 0.5 * btnWidth,
            curRatio = newWidth / parentWith,
            newTime = curRatio * mediaEle.duration;
        if (type === 1) musicPlayerUpdate(config.curTime, mediaEle, newTime);
        if (type === 2) mediaEle.volume = curRatio >= 1 ? 1 : curRatio;
        if (type === 3) videoPlayerUpdate(mediaEle, newTime);
        btn.style.left = `${newLeft}px`;
        curBar.style.width = `${newWidth}px`;
    }
}

function musicPlayerUpdate(curTime, audioEle, newTime) {
    curTime.textContent = formatSongTime(newTime);
    audioEle.currentTime = newTime;
}
function videoPlayerUpdate(videoEle, newTime) {
    // curTime.textContent = formatSongTime(newTime);
    videoEle.currentTime = newTime;
}
function volumeUpdate(mediaEle, config) {
    if (!config.vol) return;
    let str = "progress-time iconfont";
    if (mediaEle.volume >= 0 && mediaEle.volume <= 0.1) {
        config.vol.className = str + " icon-volumeyinliang";
    } else if (mediaEle.volume >= 0.01 && mediaEle.volume <= 0.5) {
        config.vol.className = str + " icon-volumeyinliangxiao";
    } else {
        config.vol.className = str + " icon-volumeyinliangda";
    }
}

export function setAudioConfig(audioEle, config, ctrl, others) {
    console.log("others: ", others)
    let btnWidth = ctrl.getBoundingClientRect().width,
        curBar = ctrl.nextElementSibling,
        parent = ctrl.parentNode,
        totoalWidth = parent.getBoundingClientRect().width,
        { ctrlSong, playBtn, lrc, lyricUp, displayLyrics, curMusicTime } = others;
    audioEle.loop = config ? config.loop : false;
    audioEle.reload = config ? config.reload : false;
    audioEle.autoplay = config ? config.autoplay : false;
    audioEle.oncanplay = function () {
        console.log('The audio can play now: display the duration for the music', lrc.timeArr.length, 'display lyrics');
        displayLyrics(lrc.lrcArr);
        config.totalTime.textContent = formatSongTime(audioEle.duration);
        this.oncanplay = null;
    }
    audioEle.onpause = function () {
        console.log('The audio stops: stop rotating the disc！');
    }
    audioEle.onended = function () {
        ctrlSong(false);
        playBtn.className = `iconfont icon-play icon-bofang3`;
    }
    audioEle.onvolumechange = function (e) {
        volumeUpdate(audioEle, config);
    }
    audioEle.addEventListener('timeupdate', (function () {
        const time = formatSongTime(this.currentTime);
        if (curMusicTime.value !== time) {
            let index = lrc.timeArr.indexOf(time), curRatio = this.currentTime / this.duration, curWidth = totoalWidth * curRatio, curLeft = curWidth - 0.5 * btnWidth;
            ctrl.style.left = `${curLeft}px`
            curBar.style.width = `${curWidth}px`;
            config.curTime.textContent = time;
            curMusicTime.value = time;
            if (index >= 0) lyricUp(index);
        }
    }).bind(audioEle));
}

export function hasEnded(mediaEle) {
    return mediaEle.currentTime === mediaEle.duration;
}

export function configPlayBtn(curAudio, playBtn, classNames, ctrlFn, parentName) {
    console.log(`Dom config once in component ${parentName}`);
    playBtn.className = `${classNames.prefix} ${curAudio.paused ? classNames.play : classNames.pause}`;
    playBtn.onclick = function (e) {
        e.stopPropagation();
        ctrlFn(curAudio.paused);
        playBtn.className = `${classNames.prefix} ${curAudio.paused ? classNames.play : classNames.pause}`;
    };
}
let curVideoTime = {
    value: ''
}
export function picInPic(video) {
    if (!document.pictureInPictureElement) {
        video.requestPictureInPicture().then(pip => {
            console.log(pip);
        }).catch(error => {
                // Video failed to enter Picture-in-Picture mode.
            });
    } else {
        document.exitPictureInPicture()
            .catch(error => {
                // Video failed to leave Picture-in-Picture mode.
            });
    }
}
export function setVideoConfig(videoEle, config, ctrl) {
    if (!ctrl) return;
    let btnWidth = ctrl.getBoundingClientRect().width,
        curBar = ctrl.nextElementSibling,
        parent = ctrl.parentNode,
        totoalWidth = parent.getBoundingClientRect().width,
        playBtn = videoEle.previousElementSibling;
    
    function clickHandler(e) {
        e.stopPropagation();
        if (this.paused) {
            this.play();
            playBtn.className = 'iconfont icon-play-full';
        } else {
            this.pause();
            playBtn.className = 'iconfont icon-play-full show';
        }
    }
    playBtn.onclick = clickHandler.bind(videoEle);
    videoEle.onclick = clickHandler.bind(videoEle);
    videoEle.ontimeupdate = function () {
        const time = formatSongTime(this.currentTime);
        if (curVideoTime.value !== time) {
            let curRatio = this.currentTime / this.duration, curWidth = totoalWidth * curRatio, curLeft = curWidth - 0.5 * btnWidth;
            console.log('ontimeupdate', time, this.currentTime);
            curVideoTime.value = time;
            ctrl.style.left = `${curLeft}px`
            curBar.style.width = `${curWidth}px`;
        }
    }
}